package com.android.powerbankpad.posutils;

import android.app.Activity;

import com.android.powerbankpad.api.ApiUrl;
import com.android.powerbankpad.config.Constants;
import com.android.powerbankpad.network.CommonalityModel;
import com.android.powerbankpad.network.NetWorkListener;
import com.android.powerbankpad.network.okHttpModel;
import com.sumup.merchant.reader.api.SumUpAPI;
import com.sumup.merchant.reader.api.SumUpLogin;
import com.sumup.merchant.reader.api.SumUpPayment;
import com.ws.universal.tools.utils.CacheUtils;
import com.ws.universal.tools.utils.LogcatUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class SumUpPosUtils implements NetWorkListener {
    private Activity activity;
    public int REQUEST_CODE_LOGIN = 100200;
    public int REQUEST_CODE_PAYMENT = 100201;
    private String amount;
    private String affiliate_keys;
    private PosListener posListener;

    public void setPosListener(PosListener posListener) {
        this.posListener = posListener;
    }

    public void initPos(Activity activity, String amount, String affiliate_keys, String accessToken) {

        this.activity = activity;
        this.amount = amount;
        this.affiliate_keys = affiliate_keys;

        SumUpLogin sumupLogin = SumUpLogin.builder(affiliate_keys).accessToken(accessToken).build();
        SumUpAPI.openLoginActivity(activity, sumupLogin, REQUEST_CODE_LOGIN);
    }


    public void reLoginSumUp(String accessToken) {
        SumUpLogin sumupLogin = SumUpLogin.builder(affiliate_keys).accessToken(accessToken).build();
        SumUpAPI.openLoginActivity(activity, sumupLogin, REQUEST_CODE_LOGIN);
    }

    public boolean isRelogin = false;

    public void getConfigSumUp(boolean isRelogin) {
        this.isRelogin = isRelogin;
        String baseUrl = CacheUtils.getString(Constants.base_url) + "/app/sumupaircard/getConfig";
        Map<String, String> params = new HashMap<>();
        okHttpModel.post(baseUrl, params, ApiUrl.sumUp_sumupaircard_Id, this);

    }


    //Step 1 读卡
    public void onDeviceScan() {

        String baseUrl = CacheUtils.getString(Constants.base_url) + "/app/sumupaircard/deviceScan";
        Map<String, String> params = new HashMap<>();
        params.put("sn", CacheUtils.getString(Constants.serial_number));
        okHttpModel.post(baseUrl, params, ApiUrl.sumUp_deviceScan_Id, this);
    }


    public void transactionSuccessful(String transactionId, String card_no, double amount) {
        String baseUrl = CacheUtils.getString(Constants.base_url) + "/app/sumupaircard/sumupLease";
        Map<String, String> params = new HashMap<>();
        params.put("pay_id", transactionId);
        params.put("card_no", card_no);
        params.put("amount", amount + "");
        params.put("sn", CacheUtils.getString(Constants.serial_number));
        okHttpModel.post(baseUrl, params, ApiUrl.sumUp_sumupLease_Id, this);

    }


    private void createOrder() {
        SumUpPayment payment = SumUpPayment.builder()
                // mandatory parameters
                .total(new BigDecimal(amount)) // minimum 1.00
                .currency(SumUpPayment.Currency.EUR)
                // optional: to be used only if the card reader supports the feature, what can be checked with `SumUpApi.isTipOnCardReaderAvailable()`
                .tipOnCardReader()
                // optional: include a tip amount in addition to the total, ignored if `tipOnCardReader()` is present
                //.tip(new BigDecimal("0.10"))
                // optional: add details
                .title("Taxi Ride")
                .receiptEmail("customer@mail.com")
                .receiptSMS("+3531234567890")
                // optional: Add metadata
                .addAdditionalInfo("AccountId", "taxi0334")
                .addAdditionalInfo("From", "Paris")
                .addAdditionalInfo("To", "Berlin")
                // optional: foreign transaction ID, must be unique!
                .foreignTransactionId(UUID.randomUUID().toString())  // can not exceed 128 chars
                // optional: skip the success screen
                .skipSuccessScreen()
                // optional: skip the failed screen
                .skipFailedScreen()
                .build();


        SumUpAPI.checkout(activity, payment, REQUEST_CODE_PAYMENT);

    }

    @Override
    public void onSucceed(JSONObject jsonData, int id, CommonalityModel commonality) throws JSONException {
        JSONObject data = jsonData.optJSONObject("data");
        switch (id) {
            case ApiUrl.sumUp_deviceScan_Id:
                if (posListener != null) {
                    posListener.deviceScanSucceed(data.optString("text"));
                }
  /*              Observable.timer(10, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Long aLong) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        createOrder();
                    }
                });*/
                createOrder();

                break;

            case ApiUrl.sumUp_sumupaircard_Id:
                LogcatUtils.e("data  " + data.toString());
                LogcatUtils.e("access_token  " + data.optString("access_token"));

                Observable.timer(30, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Long aLong) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        reLoginSumUp(data.optString("access_token"));
                    }
                });


                break;
        }
    }

    @Override
    public void onFail(JSONObject jsonData, int id, CommonalityModel commonality) {

    }

    @Override
    public void onError(int id, Exception e) {

    }


    public interface PosListener {


        //加载Ui
        void deviceScanSucceed(String text);


    }
}
